package com.wangyadong.hobby.schedule.jobtask.dsa;

import java.util.List;
import java.util.ArrayList;

class StackOfPlates {

    List<List<Integer>> heap = new ArrayList();
    int cap = -1;

    public StackOfPlates(int cap) {
        this.cap = cap;
    }

    public void push(int val) {
        if (cap == 0) return;
        if (heap.isEmpty() || heap.get(heap.size() - 1).size() >= cap) {
            //新建一个
            List<Integer> stack = new ArrayList<>(cap);
            stack.add(val);
            heap.add(stack);
        } else {
            heap.get(heap.size() - 1).add(val);
        }
    }

    public int pop() {
        if (heap.isEmpty()) return -1;
        List<Integer> last = heap.get(heap.size() - 1);
        int r = last.remove(last.size() - 1);
        if (last.size() == 0) {
            heap.remove(heap.size() - 1);
        }
        return r;
    }

    public int popAt(int index) {
        if (index < 0 || index >= heap.size()) return -1;
        List<Integer> stack = heap.get(index);
        int r = stack.remove(stack.size() - 1);
        if (stack.size() == 0) {
            heap.remove(index);
        }
        return r;
    }
}

/**
 * Your StackOfPlates object will be instantiated and called as such:
 * StackOfPlates obj = new StackOfPlates(cap);
 * obj.push(val);
 * int param_2 = obj.pop();
 * int param_3 = obj.popAt(index);
 */
//
//作者：du-shu-jiu-shi-zhuan-qian
//        链接：https://leetcode-cn.com/problems/stack-of-plates-lcci/solution/javalie-biao-lie-biao-listlistji-bai-liao-100-by-d/
//        来源：力扣（LeetCode）
//        著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。